package com.example.config;

import com.example.pojo.Configuration;
import com.example.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {


    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.selectNodes("//select");

        for (Element e : list) {
            String id = e.attributeValue("id");
            String resultType = e.attributeValue("resultType");
            String paramterType = e.attributeValue("paramterType");
            String sqlText = e.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setExecType("select");
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }

//        List<Element> inserts = rootElement.selectNodes("//insert");

        parseList(rootElement.selectNodes("//insert"), namespace, "insert");
        parseList(rootElement.selectNodes("//update"), namespace, "update");
        parseList(rootElement.selectNodes("//delete"), namespace, "delete");

    }

    void parseList(List<Element> list, String namespace, String execType) {
        for (Element e : list) {
            String id = e.attributeValue("id");
            String resultType = e.attributeValue("resultType");
            String paramterType = e.attributeValue("paramterType");
            String sqlText = e.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setExecType(execType);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
